<template>
    <div class="paddingTop chat_page">
        <head-top head-title="" goBack="true"></head-top>
        <!--        <span class="sellerinfo">{{sellername}}</span>-->
        <!--        <textarea id="chat-log" cols="50" rows="20"></textarea>-->
        <section class="msg_container">
            <section v-for="(obj,index) in msgRecord">
                <v-my-msg
                        v-if="obj.name == username"
                        :msg="obj.msg"
                        :avatar="obj.avatar"
                        :mytime="obj.time"></v-my-msg>
                <v-other-msg
                        v-else
                        :msg="obj.msg"
                        :avatar="obj.avatar"
                        :mytime="obj.time"></v-other-msg>
            </section>
        </section>

        <section class="buyfoot">
            <form class="chat_form">
                <input type="search" name="search" placeholder="想跟他说点什么呢" class="msg_input" v-model="msgValue"
                      >
                <button type="submit" class="msg_send" @click.prevent="websocketsend">发送</button>
            </form>
        </section>
    </div>
</template>

<script>
    import headTop from '../../components/header/head'
    import footGuide from '../../components/footer/footGuide'
    import {imgBaseUrl} from '../../config/env'
    import {getStore, setStore} from '../../config/mUtils'
    import myMsg from '../../components/common/myMsg'
    import otherMsg from '../../components/common/otherMsg'
    import {mapState, mapMutations} from 'vuex'

    export default {
        data() {
            return {
                msgValue: '', // 发送信息内容
                msgRecord: [],//历史消息记录
                //group_name: '',//聊天组名称
                headerMsg: '', //对话用户名
                imgBaseUrl, // 图片域名地址
                searchHistory: [], // 搜索历史记录
                showHistory: true, // 是否显示历史记录，只有在返回搜索结果后隐藏
                emptyResult: false, // 搜索结果为空时显示
                sellername: '',
                username: '',
                sellerid: '',
                userid: '',
                msglen: 0,

            }
        },
        created() {
            this.initData();
            //时间格式化
            Date.prototype.Format = function (fmt) {
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "h+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
        },
        // mounted() {
        //     //this.initData();
        //     // this.geohash = this.$route.params.geohash;
        //     // //获取搜索历史记录
        //     // if (getStore('searchHistory')) {
        //     //     this.searchHistory = JSON.parse(getStore('searchHistory'));
        //     // }
        // },
        components: {
            headTop,
            footGuide,
            'v-my-msg': myMsg,
            'v-other-msg': otherMsg,
        },
        computed: {
            ...mapState([
                'userInfo', 'geohash', 'group_name'
            ]),
        },
        methods: {
            ...mapMutations([
                'SET_GROUPNAME',
            ]),
            initData() {
                this.SET_GROUPNAME();
                this.msgRecord = new Array();
                console.log('----group_name---', this.group_name);
                this.sellername = this.$route.query.sellername;
                this.username = this.userInfo.username;
                let hm = JSON.parse(getStore(this.group_name));
                if (hm) {
                    this.msgRecord=hm;
                    console.log('--msgRecord---', hm, this.msgRecord);
                }
                this.initWebSocket();
            },

            //初始化weosocket
            initWebSocket() {
                const wsuri = `ws://127.0.0.1:8007/chat/${this.group_name}`;
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onclose = this.websocketclose;
            },

            websocketonmessage(e) {
                const redata = JSON.parse(e.data);
                if (redata.from_user == this.sellername) {
                    const obj = {
                        name: this.sellername,
                        msg: redata.message,
                        //avatar: this.chatToUser.avatar _. url,
                        time: redata.time
                    }
                    this.msgRecord.push(obj);
                } else if (redata.from_user == this.userInfo.username) {
                    console.log('消息发送成功')
                } else {
                    console.log('返回未知消息')
                }
            },

            //数据发送
            websocketsend() {
                const time = new Date();//.Format("yyyy-MM-dd hh:mm:ss")
                let obj = {
                    from_user: this.username,
                    to_user: this.sellername,
                    message: this.msgValue,
                    time: time
                }
                //发给后端的数据需要字符串化
                this.websock.send(JSON.stringify(obj));
                obj = {
                    name: this.username,
                    msg: this.msgValue,
                    //avatar: this.myUserInfo.user_image_url,
                    time: time
                }
                console.log(this.msgRecord);
                console.log(this.username);
                console.log('------00---', obj);
                this.msgRecord.push(obj);
                console.log('------00000---', this.msgRecord);
                setStore(this.group_name, this.msgRecord);
            },
            //连接建立之后执行send方法发送数据
            websocketonopen() {
                console.log('WebSocket连接成功')
            },
            //连接建立失败重连
            websocketonerror(e) {
                console.log(`连接失败的信息：${e}`)
                this.initWebSocket();
            },
            //关闭
            websocketclose(e) {
                console.log('断开连接', e);
            },

            //点击删除按钮，删除当前历史记录
            deleteHistory(index) {
                this.searchHistory.splice(index, 1);
                setStore('searchHistory', this.searchHistory);
            },
            //清除所有历史记录
            clearAllHistory() {
                this.searchHistory = [];
                setStore('searchHistory', this.searchHistory);
            },
        }
    }

</script>

<style lang="scss" scoped>
    @import '../../style/mixin';

    .chat_page {
        margin-bottom: 2rem;
    }

    .msg_container {
        width: 100%;
        overflow: scroll;
        background: #ffffff;
        margin-top: 2em;
    }

    .chat_form {
        position: fixed;
        z-index: 100;
        left: 0;
        right: 0;
        bottom: 0;
        @include wh(100%, 1.95rem);
        background-color: #fff;
        padding: 0.5rem;
        display: flex;
        height: 2.34rem;

        input {
            height: 1.5rem;
        }
    }

    .buyfoot {
        background-color: #fff;
        position: fixed;
        z-index: 100;
        left: 0;
        right: 0;
        bottom: 0;
        @include wh(100%, 1.95rem);
        display: flex;
        box-shadow: 0 -0.026667rem 0.053333rem rgba(0, 0, 0, .1);
    }

</style>

